package controllers

import (
	"errors"
	"github.com/astaxie/beego/cache"
	"github.com/astaxie/beego/utils/captcha"
	"mdblog/models/auth"
)

var (
	CaptchaError = errors.New("验证码错误")
	Cpt          *captcha.Captcha
)

func init() {
	// use beego cache system store the captcha data
	store := cache.NewMemoryCache()
	Cpt = captcha.NewWithFilter("/captcha/", store)
	Cpt.StdWidth = 140
	Cpt.StdHeight = 48
	Cpt.ChallengeNums = 4
}

type UserLoginRequest struct {
	Username  string `json:"username"`
	Password  string `json:"password"`
	CaptchaId string `json:"captcha_id"`
	Captcha   string `json:"captcha"`
}

func (request UserLoginRequest) Do(o *BlogApiController) error {
	if !Cpt.Verify(request.CaptchaId, request.Captcha) {
		return CaptchaError
	}
	user, err := auth.Authentication(request.Username, request.Username, request.Password)
	if err != nil {
		return err
	}
	o.SetSession("user", user)
	return nil
}
